#!/bin/bash

# Dify知识库管理系统 - 一键启动脚本

echo "=========================================="
echo "Dify知识库管理系统 - 启动脚本"
echo "=========================================="
echo ""

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查MySQL是否运行
echo "1. 检查MySQL服务..."
if command -v mysql &> /dev/null; then
    if mysql -h localhost -P 3306 -u root -proot -e "SELECT 1" &> /dev/null; then
        echo -e "${GREEN}✓ MySQL服务正在运行${NC}"
    else
        echo -e "${RED}✗ MySQL服务未运行或连接失败${NC}"
        echo "请启动MySQL服务并确保用户名/密码正确"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠ 未找到mysql命令，跳过检查${NC}"
fi
echo ""

# 初始化数据库
echo "2. 初始化数据库..."
if [ -f "init-database.sql" ]; then
    mysql -h localhost -P 3306 -u root -proot < init-database.sql 2>&1 | grep -v "Warning: Using a password"
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ 数据库初始化成功${NC}"
    else
        echo -e "${RED}✗ 数据库初始化失败${NC}"
        exit 1
    fi
else
    echo -e "${YELLOW}⚠ 未找到init-database.sql，跳过初始化${NC}"
fi
echo ""

# 编译后端
echo "3. 编译后端项目..."
mvn clean compile -DskipTests -q
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ 后端编译成功${NC}"
else
    echo -e "${RED}✗ 后端编译失败${NC}"
    exit 1
fi
echo ""

# 启动后端（后台运行）
echo "4. 启动后端服务..."
echo "后端日志将输出到 backend.log"
nohup mvn spring-boot:run > backend.log 2>&1 &
BACKEND_PID=$!
echo "后端进程ID: $BACKEND_PID"
echo $BACKEND_PID > backend.pid
echo ""

# 等待后端启动
echo "等待后端服务启动..."
for i in {1..30}; do
    if curl -s http://localhost:8080 > /dev/null 2>&1; then
        echo -e "${GREEN}✓ 后端服务启动成功${NC}"
        break
    fi
    if [ $i -eq 30 ]; then
        echo -e "${RED}✗ 后端服务启动超时${NC}"
        echo "请查看 backend.log 获取详细信息"
        exit 1
    fi
    sleep 2
    echo -n "."
done
echo ""

# 安装前端依赖
echo "5. 安装前端依赖..."
cd frontend
if [ ! -d "node_modules" ]; then
    npm install -q
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ 前端依赖安装成功${NC}"
    else
        echo -e "${RED}✗ 前端依赖安装失败${NC}"
        exit 1
    fi
else
    echo -e "${GREEN}✓ 前端依赖已存在${NC}"
fi
cd ..
echo ""

# 启动前端（后台运行）
echo "6. 启动前端服务..."
echo "前端日志将输出到 frontend.log"
cd frontend
nohup npm run dev > ../frontend.log 2>&1 &
FRONTEND_PID=$!
cd ..
echo "前端进程ID: $FRONTEND_PID"
echo $FRONTEND_PID > frontend.pid
echo ""

# 等待前端启动
echo "等待前端服务启动..."
for i in {1..20}; do
    if curl -s http://localhost:5173 > /dev/null 2>&1; then
        echo -e "${GREEN}✓ 前端服务启动成功${NC}"
        break
    fi
    if [ $i -eq 20 ]; then
        echo -e "${YELLOW}⚠ 前端服务可能未完全启动，请稍后访问${NC}"
        break
    fi
    sleep 2
    echo -n "."
done
echo ""

# 显示访问信息
echo "=========================================="
echo "启动完成！"
echo "=========================================="
echo ""
echo -e "${GREEN}后端服务:${NC} http://localhost:8080"
echo -e "${GREEN}前端服务:${NC} http://localhost:5173"
echo ""
echo "日志文件:"
echo "  - 后端: backend.log"
echo "  - 前端: frontend.log"
echo ""
echo "停止服务:"
echo "  ./stop-all.sh"
echo ""
echo "查看日志:"
echo "  tail -f backend.log"
echo "  tail -f frontend.log"
echo ""
